//
//  MTRefreshView.swift
//  Refresh
//
//  Created by miaozhihui on 2017/3/8.
//  Copyright © 2017年 DeKuTree. All rights reserved.
//

import UIKit

class MTRefreshView: RefreshView {

    @IBOutlet weak var buildingIconView: UIImageView!

    @IBOutlet weak var earthIconView: UIImageView!

    @IBOutlet weak var kangarooIconView: UIImageView!
    
    /// 父视图高度
    override var parentViewHeight: CGFloat {
        didSet {
            print("父视图高度 \(parentViewHeight)")
            // 23 -> 0.2
            // 126 -> 1
            // 缩放比例
            var scale: CGFloat
            // 如果小于23显示最小值
            if parentViewHeight < 23 {
                scale = 0.2
            } else if parentViewHeight >= 126 { // 如果大于最大偏移量，比例不再放大
                scale = 1
            } else {
                scale = 0.8 * (parentViewHeight - 23) / (126 - 23) + 0.2
            }
            // 根据父视图高度，调整袋鼠缩放比例
            kangarooIconView.transform = CGAffineTransform(scaleX: scale, y: scale)
        }
    }
    
    override func awakeFromNib() {
        
        // 房子
        let bImage1 = #imageLiteral(resourceName: "icon_building_loading_1")
        let bImage2 = #imageLiteral(resourceName: "icon_building_loading_2")
        buildingIconView.image = UIImage.animatedImage(with: [bImage1,bImage2], duration: 0.5)
        
        // 地球
        let animation = CABasicAnimation(keyPath: "transform.rotation")
        animation.toValue = -2 * M_PI
        animation.repeatCount = MAXFLOAT
        animation.duration = 3
        animation.isRemovedOnCompletion = false
        earthIconView.layer.add(animation, forKey: nil)
        
        // 袋鼠(随着下拉变大)
        // 实现下拉变大，上拉缩小，并且保持站在地球上，需要设置锚点和实现缩放动画
        // 1.设置锚点
        kangarooIconView.layer.anchorPoint = CGPoint(x: 0.5, y: 1)
        // 1.1设置锚点后，想要实现定位到指定锚点，需要设置下中心点
        let x = bounds.width * 0.5
        let y = bounds.height - 23
        kangarooIconView.center = CGPoint(x: x, y: y)
        
        // 2.设置袋鼠跑动动画
        let kImage1 = #imageLiteral(resourceName: "icon_small_kangaroo_loading_1")
        let kImage2 = #imageLiteral(resourceName: "icon_small_kangaroo_loading_2")
        kangarooIconView.image = UIImage.animatedImage(with: [kImage1,kImage2], duration: 0.5)
    }
}
